'use strict';

const Controller = require('egg').Controller;

function toInt(str) {
  if (typeof str === 'number') return str;
  if (!str) return str;
  return parseInt(str, 10) || 0;
}

class UserController extends Controller {
  constructor(ctx) {
    super(ctx);
    // 校验创建新用户
    this.UserCreateTransfer = {
      phone: {
        type: 'string',
        required: true,
        allowEmpty: false,
        format: /^[0-9]{11}$/,
      },
      open_id: { type: 'string', required: true, allowEmpty: false },
      nick: { type: 'string', required: true, allowEmpty: false },
      head_image: { type: 'string', required: true, allowEmpty: false },
    };

    // 更新用户信息
    this.UserUpdateTransfer = {
      phone: { type: 'string', required: true, allowEmpty: false },
      realName: {
        type: 'string',
        required: true,
        allowEmpty: false,
        format: /^[\u2E80-\u9FFF]{2,6}$/,
      },
    };

    // 登录
    this.UserLoginTransfer = {
      phone: {
        type: 'string',
        reqeuired: true,
        allowEmpty: false,
        format: /^[0-9]{11}$/,
      },
      code: { type: 'string', reqeuired: true, allowEmpty: false, length: 4 },
    };

    // 获取校验码
    this.UserValidateCodeTransfer = {
      phone: {
        type: 'string',
        required: true,
        allowEmpty: false,
        format: /^[0-9]{11}$/,
      },
    };
    this.UserInforTransfer = {
      id: { type: 'int', required: true, allowEmpty: false },
    };
  }

  /**
   * 这是一个api 文档的demo
   * @api {get} /user/:id 获取用户信息
   * @apiName GetUser
   * @apiGroup User
   *
   * @apiParam {Number} id Users unique ID.
   *
   * @apiSuccess {String} firstname Firstname of the User.
   * @apiSuccess {String} lastname  Lastname of the User.
   *
   * @apiSuccessExample Success-Response:
   *     HTTP/1.1 200 OK
   *     {
   *       "firstname": "John",
   *       "lastname": "Doe"
   *     }
   *
   * @apiError UserNotFound The id of the User was not found.
   *
   * @apiErrorExample Error-Response:
   *     HTTP/1.1 404 Not Found
   *     {
   *       "error": "UserNotFound"
   *     }
   */
  async index() {
    const ctx = this.ctx;
    const res = await ctx.model.User.findAll();
    ctx.response.success({ ctx, res });
  }


  // 获取用户信息
  async info() {
    const ctx = this.ctx;
    const id = ctx.params.id;
    if (id) {
      const res = await ctx.service.user.userInfo(id);
      console.log(res);
      ctx.response.success({ ctx, res });
    }
  }

  // 获取登录的验证码
  async loginCode() {
    const ctx = this.ctx;
    ctx.validate(this.UserValidateCodeTransfer, ctx.params);
    const phone = ctx.params.phone;
    const res = await ctx.service.user.getCode(phone);
    if (res.err) {
      ctx.status = 400;
    } else {
      ctx.response.success({ ctx, res });
    }

  }

  // 登录
  async login() {
    const ctx = this.ctx;
    ctx.validate(this.UserLoginTransfer);
    const { phone, code } = ctx.request.body;
    const res = await ctx.service.user.login(phone, code);
    if (res && !res.err) {
      ctx.response.success({ ctx, res });
    } else {
      ctx.helper.error(ctx, 2001, res.err);
    }
  }

  // 创建新用户
  async create() {
    const ctx = this.ctx;
    ctx.validate(this.UserCreateTransfer);
    const { phone, open_id, nick, head_image } = ctx.request.body;
    const res = await ctx.service.user.create({
      phone,
      open_id,
      nick,
      head_image,
    });
    ctx.status = 201;
    ctx.response.success({ ctx, res });
  }

  // 更新用户信息
  async update() {
    const ctx = this.ctx;
    const id = toInt(ctx.params.id);
    const user = await ctx.model.User.findById(id);
    if (!user) {
      ctx.status = 404;
      return;
    }
    const { name, age } = ctx.request.body;
    await user.update({ name, age });
    ctx.body = user;
  }

  // 删除用户
  async destroy() {
    const ctx = this.ctx;
    const id = toInt(ctx.params.id);
    const user = await ctx.model.User.findById(id);
    if (!user) {
      ctx.status = 404;
      return;
    }

    await user.destroy();
    ctx.status = 200;
  }
}

module.exports = UserController;
